﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using Liber;
using Liber.WEB;
using SoBusiness.Controllers;

namespace SoBusiness
{
    /// <summary>
    /// 身份验证
    /// </summary>
    public class AuthorFilter:ActionFilterAttribute
    {
        static Type noauthor = typeof(NoSessionAttribute);

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var srcRq = filterContext.RouteData;
            try
            {
                //是否需要检查Session
                if (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(noauthor, true).Length > 0 || filterContext.ActionDescriptor.GetCustomAttributes(noauthor, true).Length > 0)
                {
                    //检查引用页面
                    //if (filterContext.RequestContext.HttpContext.Request.IsLocal || filterContext.RequestContext.HttpContext.Request.Url.Host == filterContext.RequestContext.HttpContext.Request.UrlReferrer.Host)
                    //{
                    //    base.OnActionExecuting(filterContext);
                    //}
                    //else
                    //{
                    //    filterContext.Result = new RedirectResult("https://tlunion.com/Index.html");
                    //}
                    base.OnActionExecuting(filterContext);
                }
                else
                {
                    if(!SoBizController.IsLogined(filterContext.HttpContext)){

                        if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                        {
                            filterContext.HttpContext.Response.StatusCode = 401;
                            filterContext.Result = new JsonResult() { Data = FnResult<string>.Failure("AuthorFilter", "AjaxWithoutLogin").FastJson() };
                            filterContext.HttpContext.Response.End();
                            filterContext.HttpContext.ApplicationInstance.CompleteRequest();
                        }
                        else
                        {
                            filterContext.Result = new RedirectResult("/Index.html");
                            return;
                            //filterContext.Result = new RedirectResult("https://tlunion.com/Index.html");
                        }
                    }
                    else
                    {
                        base.OnActionExecuting(filterContext);
                    }
                }
            }
            catch(Exception ex)
            {
                filterContext.Result = new RedirectResult("/404.html");
            }
        }
    }


}